﻿/*----------------------------------------------------------------
// 公司名称：公司名称
//
// 产品名称：Gaf
//
// 创 建 人：netcasewqs
// 创建日期：2022/3/4
// 邮    箱：netcasewqs@qq.com
//
// Copyright (C) 2022 Gaf，保留所有权利。
//
//----------------------------------------------------------------*/

namespace Gaf.Impl;

internal class IsolationClassLoader : ClassLoader
{
    private readonly AddinActivator _activator;

    public IsolationClassLoader(AddinActivator activator) : base(
        FileUtils.GetDllPath(activator.Addin.Location, true),
        FileUtils.GetDllPath(Path.Combine(activator.Addin.Location, Constants.UnmanagedDllPathName), false),
        new AssemblyLoadContext(activator.Addin.Location, activator._framework.Options.AddinCanUninstall))
    {
        _activator = activator;
    }

    public override bool IsIsolation => true;

    public override Assembly LoadAssembly(string assemblyFilePath)
    {
        if (_activator._framework.Options.AddinAssemblyLoadMode == AddinAssemblyLoadMode.LoadFromStream)
        {
            using var sr = new FileStream(assemblyFilePath, FileMode.Open);
            var asm = _assemblyLoader.LoadFromStream(sr);
            return asm;
        }
        else
        {
            var asm = _assemblyLoader.LoadFromAssemblyPath(assemblyFilePath);
            return asm;
        }
    }

    protected override Assembly? OnAssemblyResolving(AssemblyLoadContext context, AssemblyName assemblyName)
    {
        if (assemblyName.Name != null)
        {
            if (_managedLibsPath.TryGetValue(assemblyName.Name, out var dllPath))
                return LoadAssembly(dllPath);
            if (_activator._framework._managedLibsPath.TryGetValue(assemblyName.Name, out dllPath))
                return LoadAssembly(dllPath);
        }

        return default;
    }
}